package cn.ynrcb.personnelfile.sysadmin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.ynrcb.personnelfile.sysadmin.dao.SysRegionDao;
import cn.ynrcb.personnelfile.sysadmin.entity.SysRegionEntity;
import cn.ynrcb.personnelfile.sysadmin.service.SysRegionService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("sysRegionService")
public class SysRegionServiceImpl extends ServiceImpl<SysRegionDao, SysRegionEntity> implements SysRegionService {

	@Override
	public JSONArray getByPid(String pid) {
		List<SysRegionEntity> regionList = baseMapper.findByPid(pid);
        if(CollectionUtils.isNotEmpty(regionList)) {
            JSONArray arr = converToTreeNode(regionList);
            for(int i=0;i<arr.size();i++) {
                JSONObject obj = arr.getJSONObject(i);
                obj.put("children", getByPid(Convert.toStr(obj.get("value"))));
//                obj.put("leaf", baseMapper.getCountByPId(obj.getString("id")) !=0 ? false: true );
            }
            return arr;
        }
        return null;
	}

	public JSONArray converToTreeNode(List<SysRegionEntity> list) {
        JSONArray arr = new JSONArray();
        if(CollectionUtils.isNotEmpty(list)) {
            JSONObject obj = null;
            for(SysRegionEntity region : list) {
                obj = new JSONObject();
                obj.put("label", region.getName());
                obj.put("value", region.getId());
                arr.add(obj);
            }
            return arr;
        }
        return null;
    }

}
